<template>
    <div class="container_box">
        <el-scrollbar ref="scrollbarRef" class="main_box">
            <div class="add-level-main">
                <el-form ref="formRef" class="content" :model="form" label-width="120px">
                    <el-form-item label="会员等级">
                        <div>{{ state.memberLevel }}</div>
                    </el-form-item>
                    <el-form-item label="会员名称" prop="member_level_name" :rules="rules.required">
                        <el-input
                            v-model="form.member_level_name"
                            class="input_widtn_400"
                            placeholder="请输入会员名称，不超过10个"
                            maxlength="10" />
                    </el-form-item>
                    <el-form-item
                        label="升级条件"
                        class="el-form-item_mb_15"
                        prop="member_uplevel_condition"
                        :rules="rules.member_uplevel_condition">
                        <div class="content_card">
                            <div v-if="state.memberLevel === 'VIP1'" class="input_box input_p0">无门槛</div>
                            <div v-else class="input_box input_p0">
                                <el-input-number
                                    v-model="form.member_uplevel_condition"
                                    class="input_widtn_120"
                                    :min="0"
                                    :controls="false"
                                    placeholder="请输入" />
                                <div class="input_text">成长值</div>
                            </div>
                            <div v-if="state.memberLevel === 'VIP1'" class="desc">
                                VIP1升级条件无门槛，即0成长值，不支持设置成长值门槛
                            </div>
                            <div v-else class="desc">需高于上一等级成长值：{{ state.lastLevel }}</div>
                        </div>
                    </el-form-item>
                    <div class="huiyuanquanyi">
                        <div class="label">会员权益</div>
                        <div>
                            <div v-for="(item, index) in form.memberPriority" :key="`k${index}`" class="quanyi">
                                <el-checkbox v-model="item.checked" class="duobei_checkbox" size="large">
                                    {{ item.priority_inner_name }}
                                </el-checkbox>
                                <el-form-item
                                    v-if="item.checked && item.priority_type == 2"
                                    label-width="0"
                                    :prop="`memberPriority.${index}.priority_val`"
                                    :rules="rules.required"
                                    class="input_box checkbox_input_mt">
                                    <el-input-number
                                        v-model="item.priority_val"
                                        :min="1"
                                        :max="99"
                                        :precision="1"
                                        :controls="false"
                                        placeholder="支持小数点后1位" />
                                    <span class="input_text">倍</span>
                                </el-form-item>
                            </div>
                        </div>
                    </div>
                    <div class="huiyuanquanyi">
                        <div class="label">升级礼包</div>
                        <div>
                            <div class="quanyi">
                                <el-checkbox
                                    v-model="form.member_uplevel_gift.bonus_points"
                                    :true-label="2"
                                    :false-label="1"
                                    class="duobei_checkbox"
                                    size="large"
                                    @change="onChangeBonusPoints">
                                    送积分
                                </el-checkbox>
                                <el-form-item
                                    v-if="form.member_uplevel_gift.bonus_points == 2"
                                    label-width="0"
                                    prop="member_uplevel_gift.bonus_points_point"
                                    :rules="rules.required"
                                    class="input_box checkbox_input_mt">
                                    <el-input-number
                                        v-model="form.member_uplevel_gift.bonus_points_point"
                                        :min="1"
                                        :max="99999"
                                        :precision="0"
                                        :controls="false"
                                        placeholder="请输入" />
                                    <span class="input_text">分</span>
                                </el-form-item>
                            </div>
                        </div>
                    </div>
                </el-form>
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="save">保存</el-button>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getMemberLevelInfo, addMemberLevel, updateMemberLevel } from '@/api/member/memberLevel/index';
import { getMemberPriorityList } from '@/api/member/equityManage/index';

const router = useRouter();
const route = useRoute();

const formRef = ref<any>(null);

const state = reactive<any>({
    memberLevel: '',
    nextLevel: 0,
    lastLevel: 0
});

const form = reactive<any>({
    member_level_name: '',
    member_uplevel_condition: null,
    memberPriority: [],
    member_uplevel_gift: {
        bonus_points: 1,
        bonus_points_point: null
    }
});

const validateMemberUpLevelCondition = (rule: any, value: any, callback: any) => {
    if (state.memberLevel === 'VIP1') {
        callback();
    } else {
        if (value <= state.lastLevel) {
            callback(new Error(`成长值需大于${state.lastLevel}`));
        } else if (value >= state.nextLevel && state.nextLevel > 0) {
            callback(new Error(`成长值需小于${state.nextLevel}`));
        } else if (value > 99999999) {
            callback(new Error(`成长值需小于99999999`));
        } else {
            callback();
        }
    }
};

const rules = reactive({
    required: [{ required: true, message: '此字段必填', trigger: 'blur' }],
    member_uplevel_condition: [
        { required: true, message: '此字段必填', trigger: 'blur' },
        { validator: validateMemberUpLevelCondition, trigger: 'blur' }
    ]
});

const onChangeBonusPoints = (v: any) => {
    if (v === 1) {
        form.member_uplevel_gift.bonus_points_point = null;
    }
};

const save = async () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            const member_priority = form.memberPriority
                .filter((el: any) => el.checked)
                .map((i: any) => {
                    return {
                        id: i.id,
                        priority_val: i.priority_val ? i.priority_val * 100 : 0,
                        priority_type: i.priority_type,
                        priority_id: i.priority_id
                    };
                });
            const params = {
                member_level_name: form.member_level_name,
                member_uplevel_condition: form.member_uplevel_condition,
                member_priority: member_priority,
                member_uplevel_gift: {
                    bonus_points: form.member_uplevel_gift.bonus_points,
                    bonus_points_point: form.member_uplevel_gift.bonus_points_point
                }
            };
            if (form.id) {
                params.id = form.id;
                const res = await updateMemberLevel(params);
                ElMessage.success('编辑成功');
            } else {
                const res = await addMemberLevel(params);
                ElMessage.success('保存成功');
            }
            router.back();
        }
    });
};

const getDetail = async () => {
    const params = {
        id: route.query.id
    };
    const res = await getMemberLevelInfo(params);
    form.id = res.id;
    state.memberLevel = res.member_level;
    state.lastLevel = res.last_level;
    state.nextLevel = res.next_level;
    form.member_level_name = res.member_level_name;
    form.member_uplevel_gift.bonus_points = res.member_uplevel_gift.bonus_points;
    form.member_uplevel_gift.bonus_points_point = res.member_uplevel_gift.bonus_points_point;
    form.member_uplevel_condition = res.member_uplevel_condition;
    form.memberPriority.forEach((item: any) => {
        const findItem = res.member_priority.find((i: any) => i.priority_id == item.priority_id);
        if (findItem) {
            item.id = findItem.id;
            item.checked = true;
            item.priority_val = findItem.priority_val ? findItem.priority_val / 100 : 0;
        }
    });
};

const initPriority = async () => {
    const { data } = await getMemberPriorityList({});
    const newArr: any = [];
    data.forEach((item: any) => {
        newArr.push({
            priority_id: item.id,
            priority_type: item.priority_type,
            priority_inner_name: item.priority_inner_name,
            checked: false,
            priority_val: null
        });
    });
    form.memberPriority = newArr;
    route.query.id && getDetail();
};

const goBack = () => {
    router.back();
};

onMounted(() => {
    initPriority();
    state.memberLevel = `VIP${route.query.level}`;
    state.lastLevel = +route.query.upLevel || 0;
});
</script>
<style lang="scss" scoped>
.add-level-main {
    padding: 24px;

    .huiyuanquanyi {
        display: flex;
        margin-bottom: 19px;

        .label {
            padding-right: 12px;
            padding-left: 48px;
            color: #606266;

            // &::before {
            //   margin-right: 4px;
            //   content: '*';
            //   color: var(--el-color-danger);
            // }
        }

        .quanyi {
            width: 300px;
            display: flex;
            flex-direction: column;

            .el-checkbox {
                height: auto;
                padding: 0 0 18px;
            }
        }

        .checkbox_input_mt {
            margin-bottom: 18px;
        }
    }

    :deep(.el-input-number) {
        .el-input {
            .el-input__wrapper {
                .el-input__inner {
                    text-align: left;
                }
            }
        }
    }

    .content_card {
        display: flex;
        flex: 1;
        flex-direction: column;
    }

    .el-form-item {
        margin-bottom: 24px;

        &:nth-child(n + 4) :deep(.el-form-item__error) {
            margin-top: 9px;
            margin-left: 22px;
        }
    }

    .el-form-item_mb_15 {
        margin-bottom: 15px;

        .el-form-item__content {
            .el-form-item__error {
                padding-top: 8px;
            }
        }
    }

    .desc {
        padding-top: 8px;
        color: #969696;
        line-height: 1;
    }

    .input_widtn_400 {
        width: 400px;
    }

    .input_widtn_120 {
        width: 120px;
    }

    .item_card {
        display: flex;
        flex-direction: column;

        .el-checkbox {
            height: auto;
            padding-bottom: 18px;

            &:first-child {
                padding-top: 8px;
            }

            &:last-child {
                padding-bottom: 0;
            }
        }
    }

    .shenji {
        .shenji_checkbox {
            height: auto;
            margin-bottom: 18px;
        }
    }

    .input_box {
        display: flex;
        align-items: center;
        padding-left: 22px;

        .input_text {
            margin-left: 4px;
        }
    }

    .input_mt {
        margin-top: 9px;
    }

    .input_p0 {
        padding: 0;
    }

    .item_form_item {
        margin-bottom: 0;
    }

    .next {
        display: flex;
        justify-content: flex-end;
    }
}
</style>
